package de.zainodis.kitchengnome.ui;

import static junit.framework.Assert.assertNotNull;

import java.sql.SQLException;

import android.app.Activity;
import android.os.Bundle;

import com.j256.ormlite.android.apptools.OpenHelperManager;

import de.zainodis.commons.LogCat;
import de.zainodis.kitchengnome.domainmodel.persistence.DatabaseManager;
import de.zainodis.kitchengnome.domainmodel.persistence.IItemListDao;
import de.zainodis.kitchengnome.domainmodel.persistence.IListItemDao;
import de.zainodis.kitchengnome.domainmodel.persistence.ISuggestionDao;

public class BaseActivity extends Activity {

	private static final String TAG = "BaseActivity";

	private DatabaseManager databaseHelper = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Create database helper
		getHelper();
		// Open the database
		assertNotNull("Failed to obtain writable database.", getHelper().getWritableDatabase());
		LogCat.i(TAG, "Opened database.");
	}

	@Override
	protected void onResume() {
		super.onResume();
		// Open database if its not open right now
		getHelper();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// Close database
		getHelper().close();
		LogCat.i(TAG, "Closed database.");
		// Release helper
		if (databaseHelper != null) {
			OpenHelperManager.releaseHelper();
			databaseHelper = null;
		}
	}

	protected IListItemDao getListEntryDao() {
		try {
			return getHelper().getListEntryDao();
		} catch (SQLException e) {
			LogCat.e(TAG, "Failed to obtain list entry dao.", e);
			throw new IllegalArgumentException(e);
		}
	}

	protected ISuggestionDao getSuggestionDao() {
		try {
			return getHelper().getSuggestionDao();
		} catch (SQLException e) {
			LogCat.e(TAG, "Failed to obtain suggestion dao.", e);
			throw new IllegalArgumentException(e);
		}
	}

	protected IItemListDao getItemListDao() {
		try {
			return getHelper().getItemListDao();
		} catch (SQLException e) {
			LogCat.e(TAG, "Failed to obtain item list dao.", e);
			throw new IllegalArgumentException(e);
		}
	}

	protected DatabaseManager getHelper() {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this, DatabaseManager.class);
		}
		return databaseHelper;
	}
}
